import Block from './block.js';
import Random from '../lib/random.js';
import Config from '../config/config.js';
import Direction from '../lib/direction.js';


// 定义一个食物类，继承自方块类，把方块类的属性和方法继承过来
export default class Food extends Block {
    constructor(opt) {
        opt = opt || {};
        super(opt);
        this.color = opt.color || Random.color();
    }
    render(parent) {
        let index = Math.floor(Math.random() * Config.FoodAssets.length);
        this.element.innerHTML = '<img src="'+ Config.FoodAssets[index] +'">';
        this.element.classList.add('food');
        this.element.style.lineHeight = '20px';
        let x = Random.round(0, parent.clientWidth / this.width - 1) * this.width;
        let y = Random.round(0, parent.clientHeight / this.height - 1) * this.height;
        this.x = x;
        this.y = y;
        this.element.style.top = this.y + 'px';
        this.element.style.left = this.x + 'px';
        this.direction = Direction.LEFT;
        parent.appendChild(this.element);
    }
    remove(parent) {
        parent.removeChild(this.element);
    }
    // 这里是让食物可以自己跑起来的方法，不必要认真研究
    autoRun(parent) {
        this.moveTimer = setInterval(function () {

            var nextPos = {
                x: this.x,
                y: this.y
            };

            // do{
                switch (this.direction) {
                    case Direction.TOP:
                        nextPos.y -= this.height;
                        break;
                    case Direction.RIGHT:
                        nextPos.x += this.width;
                        break;
                    case Direction.BOTTOM:
                        nextPos.y += this.height;
                        break;
                    case Direction.LEFT:
                        nextPos.x -= this.width;
                        break;
                }
                if(nextPos.x <0 || nextPos.x > parent.clientWidth - this.width || nextPos.y < 0 || nextPos.y > parent.clientHeight - this.height){
                    changeDir.call(this);
                }else{
                    this.x = nextPos.x;
                    this.y = nextPos.y;
                    // break;
                }
            // }while(true)

            this.element.style.left = this.x + 'px';
            this.element.style.top = this.y + 'px';

        }.bind(this), Config.FoodInterval);


        this.dirTimer = setInterval(changeDir.bind(this), Config.FoodDirInterval);

        function changeDir() {
            this.direction = Random.round(0,3);
        }
    }
}